// pages/cart/cart.js
import {
    Cart
} from 'cart-model.js'
var cart = new Cart();
//获取应用实例
const app = getApp()

Page({
    data: {
        allProducts: null,
        loadEnd: false,
        showDetailActive: false,
        popupList: null,
        totalPay: 0,
        totalSum: 0,
        showCouponDetail: false,
        couponList: null,
        saveAmount: 0,
        vipSaveAmount: 0,
        isVip: 0,
        needShow: false
    },
    onLoad: function (options) {
      app.aldstat.sendEvent('进入购物车');
        let sessionId = wx.getStorageSync("sessionId");
        if (sessionId === "") {
            wx.redirectTo({
                url: '/pages/getUserInfo/getUserInfo?path=/pages/cart/cart'
            })
            return
        }
        this.initData(() => {
            this.getProductCount()
        })

    },
    onShow() {
        let sessionId = wx.getStorageSync("sessionId");
        if (this.data.loadEnd && sessionId !== '') {
            this.initData(() => {
                this.getProductCount()
            })
        }
        this.setData({
            isVip: wx.getStorageSync('userStatus'),
            needShow: wx.getStorageSync('needShow') == cart.nowV ? false : true              
        })
    },
    //初始化数据封装
    initData(callback, type) {
        let data = this.data,
            params = {
                "data": {
                    "storeNo": 'S00000001'
                }
            };
        if (!(type || type === 'pulldown')) {
            wx.showLoading({
                title: '加载中',
            })
        }
        cart.getCart(params, res => {
            wx.hideLoading()
            if (res.status) {
                let newArray = []
                res.data.forEach(val => {
                    val.activityEndTime = cart.formate(val.activityEndTime, 'MM.dd hh:mm')
                    val.checkAll = true
                    val.list.forEach(list => {
                        list.addFalse = false
                        list.reduceFalse = false
                        list.checked = true
                    })
                    newArray.push(val)
                })
                this.setData({
                    allProducts: newArray,
                    loadEnd: true
                })
                this.calculateNumber()
                callback && callback()
            } else {
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        })
    },
    // 计算各种数量总价
    calculateNumber(){
        let { allProducts } = this.data,
            pay = 0,
            sum = 0,
            saveAmount = 0,
            vipSaveAmount = 0;
        allProducts.forEach(val => {
            val.list.forEach(list => {
                if(list.checked){
                    pay += (list.goodsPrice * 100 * list.goodsNum * 100) / 10000
                    sum += list.goodsNum
                    saveAmount += (list.originalPrice * 100 - list.goodsPrice * 100) * list.goodsNum;
                    vipSaveAmount += (list.discountPrice * 100 - list.memberPrice * 100) * list.goodsNum;
                }
            })
        })
        this.setData({
            totalPay: this.returnFloat(pay),
            totalSum: sum,
            saveAmount: saveAmount / 100,
            vipSaveAmount: vipSaveAmount / 100
        })
    },
    //列表增加
    add(e) {
        let id = cart.getDataSet(e, "id")
        let index = cart.getDataSet(e, "index")
        let i = cart.getDataSet(e, "i")
        this.addReduceCommon('add', id, index, i)
        this.getProductCount();
    },
    //列表减少
    reduce(e) {
        let id = cart.getDataSet(e, "id")
        let index = cart.getDataSet(e, "index")
        let i = cart.getDataSet(e, "i")
        this.addReduceCommon('reduce', id, index, i)
        this.getProductCount();
    },
    // 列表页增加减少请求封装
    addReduceCommon(type, id, index, activityId) {
        let allProducts = this.data.allProducts
        let nowGoods = null
        let parentIndex
        console.log(type, id)
        allProducts.forEach((val, i) => {
            if (val.activityId == activityId) {
                parentIndex = i
                console.log(parentIndex, i)
            }
        })
        let val = allProducts[parentIndex].list[index]
        console.log('val', val)
        if (type == 'add') {
            if (val.stockNum > val.goodsNum) {
                wx.showLoading({
                    title: '加载中'
                })
                val.goodsNum++
            }
        } else {
            if (val.goodsNum == 1) {

            } else {
                wx.showLoading({
                    title: '加载中'
                })
                val.goodsNum--
            }
        }
        nowGoods = {
            "data": {
                "storeNo": "S00000001",
                "goodsId": "" + id,
                "specsName": "" + val.specsName,
                "goodsName": "" + val.goodsName,
                "goodsNum": "" + val.goodsNum,
                "goodsPrice": "" + val.goodsPrice,
                "originalPrice": "" + val.originalPrice,
                "discountPrice": "" + val.discountPrice,
                "goodsColor": "" + val.goodsColor,
                "goodsPic": "" + val.goodsPic,
                "oldGoodsId": "" + id,
                "oldSpecsName": "" + val.specsName
            }
        }
        cart.upadateCart(nowGoods, res => {
            if (res.status) {
                wx.hideLoading()
                this.setData({
                    allProducts
                })
                this.calculateNumber()
            } else {
                wx.hideLoading()
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        })
    },
    // 删除商品
    deleteGoods(e) {
        console.log(cart.getDataSet(e, "id"), cart.getDataSet(e, 'specsname'))
        var that = this
        let pay = 0;
        let sum = 0
        let params = {
            "data": {
                "storeNo": "S00000001",
                "goodsId": "" + cart.getDataSet(e, "id"),
                "specsName": "" + cart.getDataSet(e, 'specsname')
            }
        }
        wx.showModal({
            title: '提示',
            content: '确认删除吗？',
            success: function (res) {
                if (res.confirm) {
                    wx.showLoading({
                        title: '加载中',
                    })
                    cart.deleteCart(params, res => {
                        wx.hideLoading()
                        console.log(res)
                        let status = res.status
                        if (status) {
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 1500,
                                success() {
                                    setTimeout(() => {
                                        that.initData(() => {});
                                    }, 1000)
                                }
                            })
                        } else {
                            wx.hideLoading()
                            wx.showToast({
                                title: '服务器错误',
                                icon: 'none'
                            })
                        }
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },


    //去付款
    onOrderConfirme(e) {
        let id = cart.getDataSet(e, "id")
        let allProducts = this.data.allProducts
        let wxUid = wx.getStorageSync('wxUid')
        let phone = wx.getStorageSync('phone')
        let result = []
        let that = this
        allProducts.forEach((val, i) => {
            if (val.activityId == id && val.activityStatus == 1) {
                val.list.forEach(list => {
                    if(list.checked){
                        result.push({
                            "goodsId": +list.goodsId,
                            "specsName": list.specsName,
                            "storeNo": "S00000001",
                            "wxUid": wxUid,
                            "activityId": '' + id
                        })
                    }
                })
            }
        })
        console.log('result', result)
        let params = {
            "data": {
                "list": result
            }
        }
        if (result.length <= 0) {
            wx.showToast({
                title: '您还没有选择宝贝哦！',
                icon: 'none'
            })
            return
        }
        console.log('phone', phone)
        if (phone === '') {
            wx.navigateTo({
                url: '/pages/signin/signin?path=/pages/cart/cart',
            })
            return
        }
        cart.createOrderAndDetails(params, res => {
            if (res.status) {
                this.setData({
                    showDetailActive: false
                })
                wx.navigateTo({
                    url: "/pages/orderDetail/orderDetail?orderId=" + res.data.orderId
                })
            } else {
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        })

    },
    //保留两位小数
    returnFloat: function (value) {
        var value = Math.round(parseFloat(value) * 100) / 100;
        var xsd = value.toString().split(".");
        if (xsd.length == 1) {
            value = value.toString() + ".00";
            return value;
        }
        if (xsd.length > 1) {
            if (xsd[1].length < 2) {
                value = value.toString() + "0";
            }
            return value;
        }
    },

    //计算商品选择数量
    getProductCount() {
        let allProducts = this.data.allProducts;
        let crtNum = 0;
        allProducts && allProducts.forEach(val => {
            val.list.forEach(list => {
                crtNum += parseInt(list.goodsNum);
            })
        })
        //设置购物车右上角红色点
        if (crtNum == 0) {
            wx.hideTabBarRedDot({
                index: 1
            })
        } else {
            wx.showTabBarRedDot({
                index: 1
            })
            wx.setTabBarBadge({
                index: 1,
                text: '' + crtNum,
            })
        }
    },
    //   点击购物车
    showCart() {
        let {
            showDetailActive,
            allProducts
        } = this.data
        let newArray = []
        let selSize = 0
        allProducts.forEach(val=>{
            for(var i = 0; i < val.list.length; i++){
                if(val.list[i].checked){
                    selSize++
                    break                    
                }
            }
        })
        console.log('selSize',selSize)
        if (selSize === 1) {
            let phone = wx.getStorageSync('phone')
            let wxUid = wx.getStorageSync('wxUid')            
            let result = []
            let that = this
            this.data.allProducts.forEach(val=>{
                if (val.activityStatus === 1){
                    val.list.forEach(list=>{
                        if(list.checked){
                            result.push({
                                "goodsId": +list.goodsId,
                                wxUid,
                                "storeNo": "S00000001",
                                "specsName": list.specsName,
                                "activityId": '' + allProducts[0].activityId
                            })
                        }
                    })
                }
            })
            let params = {
                "data": {
                    "list": result
                }
            }
            console.log(params, 'result', result.length)
            if (result.length <= 0) {
                wx.showToast({
                    title: '您还没有选择宝贝哦！',
                    icon: 'none'
                })
                return
            }
            if (phone === '') {
                wx.navigateTo({
                    url: '/pages/signin/signin?path=/pages/cart/cart',
                })
                return
            }
            cart.createOrderAndDetails(params, res => {
                if (res.status) {
                    this.setData({
                        showDetailActive: false
                    })
                    wx.navigateTo({
                        url: "/pages/orderDetail/orderDetail?orderId=" + res.data.orderId
                    })
                } else {
                    wx.showToast({
                        title: '服务器错误',
                        icon: 'none'
                    })
                }
            })
            return
        }
        
        if (!showDetailActive) {
            allProducts.forEach(val => {
                let activityId = val.activityId,
                    activityName = val.activityName,
                    num = 0,
                    price = 0;
                if (val.activityStatus === 1) {
                    val.list.forEach(list => {
                        if (list.checked) {
                            num += list.goodsNum;
                            price += (list.goodsPrice * 1000 * list.goodsNum);
                            console.log(list.goodsPrice)
                        }
                    })
                    if (num > 0){
                        newArray.push({
                            activityId,
                            activityName,
                            num,
                            price: price / 1000
                        })
                    }
                    console.log(newArray)
                }
            })
            if(newArray.length > 0){
                this.setData({
                    showDetailActive: true
                })
                this.setData({
                    popupList: newArray
                })
            }else{
                wx.showToast({
                    title: '请勾选结算商品',
                    icon: 'none'
                })
            }
        }else{
            this.setData({
                showDetailActive: false
            })
        }
    },
    // 清空购物车
    clearCart() {
        let that = this
        wx.showModal({
            title: '提示',
            content: '确定清空购物车吗？',
            success(res) {
                if (res.confirm) {
                    cart.clearCart({
                        data: {
                            storeNo: 'S00000001'
                        }
                    }, res => {
                        if (res.status) {
                            wx.hideTabBarRedDot({
                                index: 1
                            })
                            wx.showToast({
                                title: '清空成功',
                                icon: 'success',
                                duration: 1500,
                                success() {
                                    setTimeout(() => {
                                        that.initData()
                                    }, 1500)
                                }
                            })
                        }
                    })
                }
            }
        })
    },
    onPullDownRefresh() {
        this.initData(() => {
            wx.stopPullDownRefresh()
        }, 'pulldown')
        this.getProductCount()
    },
    // 切换显示优惠券
    toggleCoupon(e) {
        let {
            showCouponDetail,
        } = this.data
        let id = cart.getDataSet(e, 'id')
        if (!showCouponDetail) {
            wx.showLoading({
                title: '加载中...',
            })
            let params = {
                data: {
                    activityId: id
                }
            }
            cart.getCouponList(params, res => {
                wx.hideLoading()
                if (res.status) {
                    res.data.forEach(val => {
                        val.startTime = cart.formate(val.startTime, 'yyyy-MM-dd')
                        val.endTime = cart.formate(val.endTime, 'yyyy-MM-dd')
                        if (val.pcuEndTime && val.pcuStartTime) {
                            val.pcuEndTime = cart.formate(val.pcuEndTime, 'yyyy-MM-dd')
                            val.pcuStartTime = cart.formate(val.pcuStartTime, 'yyyy-MM-dd')
                        }

                    })
                    this.setData({
                        couponList: res.data,
                        showCouponDetail: true
                    })
                } else {
                    wx.showToast({
                        icon: 'none',
                        title: '服务器错误',
                    })
                }
            })
        } else {
            this.setData({
                showCouponDetail: false
            })
        }
    },
    //领取优惠券
    getCoupon(e) {
        let id = cart.getDataSet(e, 'id')
        let index = cart.getDataSet(e, 'index')
        let params = {
            data: {
                couponIds: '' + id
            }
        }
        cart.getCoupon(params, res => {
            if (res.status) {
                if (res.data.length > 0) {
                    wx.showToast({
                        title: '领取成功',
                    })
                } else {
                    wx.showToast({
                        title: '该券已拥有！',
                    })
                }
                let now = "couponList[" + index + "].isReceived"
                this.setData({
                    [now]: 1
                })
            } else {
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        })
    },
    // 跳转购买会员页
    jumpOrdinary() {
        let { activeId } = this.data
        let phone = wx.getStorageSync("phone");
        if (phone === "") {
            wx.navigateTo({
                url: '/pages/signin/signin?path=/pages/role/ordinary/ordinary',
            })
        } else {
            wx.navigateTo({
                url: '/pages/role/ordinary/ordinary',
            })
        }
    },
    // 头部按钮切换
    checkAll(e){
        let idx = cart.getDataSet(e,'index');
        let { allProducts} = this.data
        allProducts[idx].checkAll = !allProducts[idx].checkAll
        allProducts[idx].list.forEach(val=>{
            if (allProducts[idx].checkAll){
                val.checked = true
            }else{
                val.checked = false
            }
        })
        this.setData({
            allProducts,
        })
        this.calculateNumber()
    },
    // 单个按钮切换
    checkToggle(e){
        let index = cart.getDataSet(e, 'index');
        let idx = cart.getDataSet(e, 'idx');
        let { allProducts } = this.data
        let checked = "allProducts["+index+"].list["+idx+"].checked"
        this.setData({
            [checked]: !allProducts[index].list[idx].checked,
        })
        this.data.allProducts.forEach((val,i)=>{
            let checked = val.list.some(list=>{
                return list.checked === false
            })
            let checkAll = "allProducts["+ i +"].checkAll"
            this.setData({
                [checkAll]: checked ? false : true
            })
        })
        this.calculateNumber()
    },
    // 跳转商品详情
    jumpProductDetail(e){
        let id = cart.getDataSet(e,'id');
        wx.navigateTo({
            url: '/pages/product/product?id='+ id,
        })
    }
})